import { SocketRespWrap, SocketState } from "../../core/module/socket/BaseTypes"
import { Protocol } from "../../proto/msg"
import { app } from "../app/App"
import { SceneEnum } from "../share/Enum"

export class LoginModel {

    private _initServer(callback?) {
        app.net.connect(app.model.global.serverIp, app.model.global.lobbyPort, callback)
    }

    accountLoginReq(account: string, password: string, callback?) {
        this._initServer(() => {
            app.net.sendData(Protocol.GAME_LOGIN, { account, password }, (resp: SocketRespWrap) => {
                if (resp.code == proto.CODE.SUCCESS) {
                    const data = resp.body as proto.LoginResp
                    const userBaseInfo = data.userBaseInfo
                    console.log("登录成功")
                    //保存账号信息
                    app.model.global.saveAccountInfo(account, password)
                    //保存玩家信息
                    app.model.user.saveUserBaseInfo(userBaseInfo.userId, userBaseInfo.nickname);
                    if (data.roomInfo.roomId) {
                        //保存房间信息
                        app.model.game.saveRoomInfo(data.roomInfo.roomId, data.roomInfo.kindId)
                    }
                    callback && callback(data.roomInfo.roomId > 0)
                }
                else app.toast.showAlert("登录失败 system code: " + resp.code)
            })
        })
    }

    accountRegisterReq(account: string, password: string, callback?) {
        this._initServer(() => {
            app.net.sendData(Protocol.GAME_LOGIN, { account, password }, (resp: SocketRespWrap) => {
                if (resp.code == proto.CODE.SUCCESS) {
                    const data = resp.body as proto.UserBaseInfo
                    console.log("注册成功")
                    //保存账号信息
                    app.model.global.saveAccountInfo(account, password)
                    //保存玩家信息
                    app.model.user.saveUserBaseInfo(data.userId, data.nickname);
                    callback && callback()
                }
                else app.toast.showAlert("登录失败 system code: " + resp.code)
            })
        })
    }

    silentLogin() {
        this.accountLoginReq(app.model.global.account, app.model.global.password, () => {
            app.scene.startScene(SceneEnum.Lobby)
        })
    }
}


